/**
 * 
 */
package org.apache.shiro.tutorial;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.Factory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.rico.utils.SaltGenerator;
import cc.rico.utils.Sha256HashUtil;

/**
 * @author rico 2016年6月11日
 *
 */
public class Tutorial {
	private static final transient Logger logger = LoggerFactory.getLogger(Tutorial.class);

	/**
	 * @param args
	 */
	@Test
	public void testLogin() {
		logger.info("My First Apache Shiro Application");
		
		this.initSecurityManager("classpath:shiro-tutorial.ini");
		
		// get the currently executing user:
		Subject currentUser = SecurityUtils.getSubject();
		
		// Do some stuff with a Session (no need for a web or EJB container!!!)
		Session session = currentUser.getSession();
		session.setAttribute("username", "rico");
		String value = (String) session.getAttribute("username");
        if (value.equals("aValue")) {
            logger.info("Retrieved the correct value! [" + value + "]");
        }
        
        if(currentUser.isAuthenticated()) {
        	logger.info("##username={} already log in......", currentUser.getPrincipal());
        	return;
        }
        
        try {
	        // 	let's login the current user so we can check against roles and permissions:
        	//String encodePassword = new Sha256Hash("admin", null, 1024).toBase64();
        	//String encodeCredentials = new Sha256HashUtil().encode("admin");
        	String encodeCredentials = "admin";
        	
        	UsernamePasswordToken token = new UsernamePasswordToken("rico", encodeCredentials);
        	token.setRememberMe(true);
        	currentUser.login(token);
        	
        } catch ( UnknownAccountException uae ) {
        	logger.error(uae.getMessage(), uae);
        } catch ( IncorrectCredentialsException ice ) {
            logger.error(ice.getMessage(), ice);
        } catch ( LockedAccountException lae ) {
        	logger.error(lae.getMessage(), lae);
        } catch ( AuthenticationException ae ) {
        	logger.error(ae.getMessage(), ae);
        }
        
        logger.info("##isAuthentication={}", currentUser.isAuthenticated());
        logger.info("##permission[/perm1]={}", currentUser.isPermitted("/perm1"));
        logger.info("##role[admin]={}", currentUser.hasRole("admin"));
        
        logger.info("##principles = {}", currentUser.getPrincipals());
        
        // say who they are:
        // print their identifying principal (in this case, a username):
//        logger.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//        
//        // test a role:
//        if (currentUser.hasRole("schwartz")) {
//            logger.info("May the Schwartz be with you!");
//        } else {
//            logger.info("Hello, mere mortal.");
//        }
//
//        // test a typed permission (not instance-level)
//        if (currentUser.isPermitted("lightsaber:weild")) {
//            logger.info("You may use a lightsaber ring.  Use it wisely.");
//        } else {
//            logger.info("Sorry, lightsaber rings are for schwartz masters only.");
//        }
//
//        // a (very powerful) Instance Level permission:
//        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
//            logger.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
//                    "Here are the keys - have fun!");
//        } else {
//            logger.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
//        }

        currentUser.logout();
        
	}
	
	@Test
	public void testGenerateSalt() {
		ByteSource source = SaltGenerator.generateSalt();
		logger.info("source = {}", source);
	}
	
	/**
	 * init securityManager
	 * @param config
	 * @return
	 */
	private void initSecurityManager(String config) {
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(config);
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
	}

}
